package com.example.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Arrays;

@ControllerAdvice(annotations = {RestController.class, Controller.class})

@Slf4j
public class ControllerExceptions {
    @ResponseBody
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String>exception(SQLIntegrityConstraintViolationException ex) {
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] error = ex.getMessage().split(" ");
            String msg = error[2] + "已存在";
            log.error(msg);
            log.error(ex.getMessage());
            return R.error(msg);
        }
        return R.error("未知错误");
    }

}
